#include "prec.h"
#include "pagecontainer.h"

#include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(PageArray)

PageContainer::PageContainer()
{
	m_active = -1;
}

PageContainer::~PageContainer()
{

}

bool PageContainer::AddPage( wxWindow* page )
{
	page->SetPosition(wxPoint(0,0));
	page->SetSize(m_rect.GetSize());
	page->Layout();
	m_pages.Add(page);

	return true;
}

bool PageContainer::InsertPage( wxWindow* page, size_t idx )
{
	page->SetPosition(wxPoint(0,0));
	page->SetSize(m_rect.GetSize());
	page->Layout();

	if (idx >= m_pages.GetCount())
		m_pages.Add(page);
	else
		m_pages.Insert(page, idx);

	return true;
}

bool PageContainer::MovePage( wxWindow* page, size_t new_idx )
{
	int idx = GetIdxFromWindow(page);
	if (idx == -1)
		return false;

	// get page entry, make a copy of it
	wxWindow* p = GetPage(idx);

	// remove old page entry
	RemovePage(page);

	// insert page where it should be
	InsertPage(page, new_idx);

	return true;
}

bool PageContainer::RemovePage( wxWindow* page )
{
	size_t i, page_count = m_pages.GetCount();
	for (i = 0; i < page_count; ++i)
	{
		wxWindow* wnd = m_pages.Item(i);
		if (page == wnd)
		{
			m_pages.RemoveAt(i);
			return true;
		}
	}

	return false;
}

bool PageContainer::SetActivePage( wxWindow& page )
{
	int idx = GetIdxFromWindow(&page);
	if (idx == -1)
		return false;

	m_active = idx;

	DoShowHide();
	return true;
}

bool PageContainer::SetActivePage( size_t page )
{
	m_active = page;

	DoShowHide();
	return true;
}

void PageContainer::SetNoneActive()
{
	m_active = -1;
}

wxWindow* PageContainer::GetWindowFromIdx( size_t idx ) const
{
	if (idx >= m_pages.GetCount())
		return NULL;

	return m_pages[idx];
}

int PageContainer::GetIdxFromWindow( wxWindow* page ) const
{
	size_t i, page_count = m_pages.GetCount();
	for (i = 0; i < page_count; ++i)
	{
		wxWindow* wnd = m_pages.Item(i);
		if (page == wnd)
			return i;
	}
	return -1;
}

void PageContainer::DoShowHide()
{
	PageArray& pages = GetPages();
	size_t i, page_count = pages.GetCount();

	// show new active page first
	for (i = 0; i < page_count; ++i)
	{
		wxWindow* page = pages.Item(i);
		page->Show(i == m_active);
	}
}

void PageContainer::SetRect( const wxRect& rect )
{
	m_rect = rect;

	PageArray& pages = GetPages();
	size_t i, page_count = pages.GetCount();

	// show new active page first
	for (i = 0; i < page_count; ++i)
	{
		wxWindow* page = pages.Item(i);
		page->SetSize(rect.GetSize());
	}
}